import { ElMessage } from 'element-plus';
interface Options {
  method?:
    | 'get'
    | 'GET'
    | 'HEAD'
    | 'PATCH'
    | 'POST'
    | 'PUT'
    | 'DELETE'
    | 'CONNECT'
    | 'OPTIONS'
    | 'TRACE'
    | 'head'
    | 'patch'
    | 'post'
    | 'put'
    | 'delete'
    | 'connect'
    | 'options'
    | 'trace';
  lazy?: boolean;
  server?: boolean;
  params?: any;
  headers?: any;
  // prefix?: string;
  //
  // timeout?: number;
  // timeoutMessage?: string;

  // data?: any;
  // errorHandler?: (error: any) => void;
}

const parseParams = (data: any) => {
  try {
    var tempArr = [];
    for (var i in data) {
      var key = encodeURIComponent(i);
      var value = encodeURIComponent(data[i]);
      tempArr.push(key + '=' + value);
    }
    var urlParamsStr = tempArr.join('&');
    return urlParamsStr;
  } catch (err) {
    return '';
  }
};

export const useRequest = async (url: string, options: Options = {}) => {
  const config = useRuntimeConfig();
  if (!options.method) {
    options.method = 'GET';
  }
  if (!options.headers) {
    options.headers = {
      'Content-Type': 'application/json',
    };
  }
  const requestConfig: any = {
    baseURL: config.public.baseApiUrl,
    headers: options.headers,
    method: options.method,
    lazy: options.lazy || true,
    server: options.server || true,
  };
  if (!options.params) {
    options.params = {
      project_id: config.public.projectId,
    };
  } else {
    options.params.project_id = config.public.projectId;
  }
  if (options.method === 'GET' || options.method === 'get') {
    url = url + '?' + parseParams(options.params);
  } else {
    requestConfig.params = options.params;
  }
  let res: any = await useFetch(url, {
    ...requestConfig,
  });
  res = JSON.parse(JSON.stringify(res));
  if (res.data._rawValue) {
    if (res.data._rawValue.status !== 20000) {
      ElMessage.error(res.data._rawValue.message);
    }
    return res.data._rawValue;
  } else {
    ElMessage.error('接口错误');
    return { status: 4444, message: '接口错误' };
  }
};
